<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <!--      <el-form-item label="系统模块" prop="title">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.title"-->
      <!--          placeholder="请输入系统模块"-->
      <!--          clearable-->
      <!--          style="width: 240px;"-->
      <!--          size="small"-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="操作人员" prop="operName">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入操作人员"
          clearable
          style="width: 240px;"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="operType">
        <el-select
          v-model="queryParams.operType"
          placeholder="操作类型"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in operTypeOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="statusOptions">
        <el-select
          v-model="queryParams.status"
          placeholder="操作状态"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="操作时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleClean"
        >清空
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    </el-row>

    <el-table :header-cell-style="{padding:10+'px' + ' ' + 0}" :cell-style="{padding:7+'px' + ' ' + 0}" ref="tables"
              v-loading="loading" :data="list" @selection-change="handleSelectionChange"
              :default-sort="defaultSort" @sort-change="handleSortChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="日志编号" align="center" prop="id"/>
      <el-table-column label="操作人员" align="center" prop="username"/>
      <el-table-column label="操作类型" align="center" prop="operType"/>
      <el-table-column label="请求方法" align="center" prop="requestType"/>
      <el-table-column label="消耗时间(ms)" align="center" prop="costTime"/>
      <el-table-column label="操作状态" align="center" prop="status">
        <template slot-scope="scope">
          <div>{{scope.row.status === 0 ? '成功' : '失败'}}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作日期" align="center" prop="operTime" sortable="custom"
                       :sort-orders="['descending', 'ascending']" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.operTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row,scope.index)"
          >详细
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      layout="total, sizes,prev, pager, next,jumper"
      v-show="total>0"
      :total="total"
      background
      :page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 50]"
      :current-page.sync="queryParams.pageNum"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 操作日志详细 -->
    <el-dialog title="操作日志详细" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px" size="mini">
        <el-row>
          <el-col :span="12">
            <!--            <el-form-item label="操作模块：">{{ form.title }} / {{ typeFormat(form) }}</el-form-item>-->
            <el-form-item label="操作模块：">test</el-form-item>
            <el-form-item
              label="登录信息："
            >{{ form.username }} / {{ form.operIp }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请求地址：">{{ form.url }}</el-form-item>
            <el-form-item label="请求方式：">{{ form.requestType }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="操作方法：">{{ form.method }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="操作描述：">{{ form.content }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="请求参数：">{{ form.operParam }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="返回参数：">{{ form.result }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作状态：">
              <div v-if="form.status === 0">正常</div>
              <div v-else-if="form.status === 1">失败</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作时间：">{{ parseTime(form.operTime) }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="异常信息：" v-if="form.status === 1">{{ form.errorMsg }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { list,del,clear,download } from '@/api/admin/operlog/operlog'

  export default {
    name: 'Operlog',
    dicts: ['sys_oper_type', 'sys_common_status'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 表格数据
        list: [],
        // 是否显示弹出层
        open: false,
        // 日期范围
        dateRange: '',
        operTypeOptions: [
          {
            value: 0,
            label: '其他'
          },
          {
            value: 1,
            label: '删除'
          },
          {
            value: 2,
            label: '更新'
          },
          {
            value: 3,
            label: '查询'
          },
          {
            value: 4,
            label: '新增'
          },
          {
            value: 5,
            label: '登录'
          },
          {
            value: 6,
            label: '导入'
          },
          {
            value: 7,
            label: '导出'
          },
          {
            value: 8,
            label: '清空'
          }
        ],
        statusOptions:[
          {
            value:0,
            label:'成功'
          },
          {
            value:1,
            label:'失败'
          }
        ],
        // 默认排序
        defaultSort: { prop: 'operTime', order: 'descending' },
        // 表单参数
        form: {},
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          username: undefined,
          operType: undefined,
          status: undefined,
          sort:undefined,
        }
      }
    },
    created() {
      this.getList()
    },
    methods: {
      /** 查询登录日志 */
      getList() {
        this.loading = true
        let operTimes = undefined
        if (this.dateRange) {
          operTimes = this.dateRange[0] + '~' + this.dateRange[1]
        }
        const reqData = {
          username: this.queryParams.username,
          operTimes: operTimes,
          status:this.queryParams.status,
          operType:this.queryParams.operType,
          sort:this.queryParams.sort
        }
        list(reqData, this.queryParams.pageSize, this.queryParams.pageNum).then(response => {
          const resData = response.data
          if (response.flag) {
            this.list = resData.tbLogs
            this.total = resData.total
            this.list = this.list.map(item => {
              item.operType = this.getOperTypeStr(item.operType)
              return item
            })
          } else {
            this.$message.error(resData.messge)
          }
          this.loading = false
        }).catch(err => {
          console.info(err)
          this.loading = false
        })
      },
      handleSizeChange(size) {
        this.queryParams.pageSize = size
        this.getList()
      },
      handleCurrentChange(currentPage) {
        this.queryParams.pageNum = currentPage
        this.getList()
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = undefined
        this.queryParams.username = undefined
        this.queryParams.operType = undefined
        this.handleQuery()
      },
      /** 多选框选中数据 */
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.multiple = !selection.length
      },
      /** 排序触发事件 */
      handleSortChange(column, prop, order) {
        console.info(column.order)
        // this.queryParams.currentPage = 1;
        this.queryParams.sort = column.order;
        this.getList();
      },
      /** 详细按钮操作 */
      handleView(row) {
        this.open = true
        this.form = row
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        console.info(row)
        const operIds = row.id || this.ids
        const flag = confirm('是否确认删除日志编号为"' + operIds + '"的数据项？')
        if (!flag){
          return
        }
        const reqData = {
          ids:operIds
        }
        del(reqData).then(res=>{
          console.info(res)
          if (res.flag){
            this.$message.success(res.message);
            this.getList();
          }else{
            this.$message.error(res.messgae);
          }
        }).catch(err=>{console.info(err)})
      },
      /** 清空按钮操作 */
      handleClean() {
        const flag = confirm("是否确认清空所有操作日志数据项？");
        if (!flag){
          return
        }
        clear().then(res=>{
          if (res.flag){
            this.$message.success(res.message);
            this.getList();
          }else{
            this.$message.error(res.message);
          }
        }).catch(err=>{console.info(err)})
      },
      /** 导出按钮操作 */
      handleExport() {
        download().then(res => {
          console.info(res)
          const fileName = res.headers['content-disposition'].split('filename=')[1]
          console.info(fileName)
          const blob = new Blob([res.data])
          // 前端获取业务码，成功执行正常业务
          const downloadElement = document.createElement('a')
          const href = window.URL.createObjectURL(blob) // 创建下载的链接
          downloadElement.href = href
          downloadElement.download = fileName // 下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() // 点击下载
          document.body.removeChild(downloadElement) // 下载完成移除元素
          window.URL.revokeObjectURL(href) // 释放掉blob对象
        }).catch(err => {})
      },
      getOperTypeStr(operType) {
        const operTypeStr = ['其他','删除', '更新', '查询', '新增', '登录', '导入', '导出',"清空数据" ]
        return operTypeStr[operType]
      }
    }
  }
</script>

<style scoped>
  .el-form-item {
    margin-bottom: 10px;
  }
</style>
